package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author: atguigu
 * @create: 2025-07-21 09:49
 */
@Slf4j
@Aspect
@Component
public class GuiGuLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 为了代码规范：认证状态校验注解只能用在api包下，且只有使用@GuiGuLogin注解的方法才能被增强
     *
     * @param pjp 目标方法对象
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(guiGuLogin)")
    public Object doBasicProfiling(ProceedingJoinPoint pjp, GuiGuLogin guiGuLogin) throws Throwable {
        log.info("一、前置逻辑");
        //1.获取用户令牌，用于查询redis中用户基本信息
        //1.1 获取请求对象
        //1.1.1 获取请求上下文对象 RequestAttributes是接口
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //1.1.2 获取请求对象 ServletRequestAttributes是实现类
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();

        //1.2 获取请求头：token
        String token = request.getHeader("token");

        //2.查询当时在登录成功后存入redis中用户基本信息 UserInfoVo
        //2.1. 构建查询用户信息Redis的Key 注意：一定要跟登录成功存入Redis一致
        String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        //2.2 查询Redis中用户信息
        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(loginKey);

        //3.如果目标方法要求必须登录但查询Redis用户信息为空，抛出登录异常，响应业务状态码208
        if (guiGuLogin.required() && userInfoVo == null) {
            log.error("用户未登录,引导用户登录");
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }

        //4.如果查询Redis存在用户信息，将用户ID存入ThreadLocal中方便JavaEE三层任意层获取用户ID
        if (userInfoVo != null) {
            AuthContextHolder.setUserId(userInfoVo.getId());
        }
        log.info("二、目标方法执行");
        Object retVal = pjp.proceed();
        log.info("三、后置逻辑");

        //5.清理ThreadLocal防止内存泄漏
        AuthContextHolder.removeUserId();
        return retVal;
    }


}
